/**
 * WechatFile.js
 * 
 * @description :: TODO: You might write a short summary of how this model works
 *              and what it represents here.
 * @docs :: http://sailsjs.org/#!documentation/models
 */
var fs = require('fs');
var rndstring = require("randomstring");

module.exports = {

	attributes : {
		
		form : {
			model : 'Form',
		},
		
		post : {
			model : 'Post',
		},
		
		mediaid : {
			type : 'string',
			required : true
		},
		
		filename : {
			type : 'string',
		},
	},
	
	beforeCreate: function(file, cb){
		var filename = rndstring.generate(20);
		file.filename = filename;
		cb();
	},
	
	afterCreate: function(file, cb){
		
		WechatService.downloadFile(file.mediaid, function(err, result, res){
			
			fs.writeFile(sails.config.appPath + sails.config.application.uploadPath + '/' +  file.filename + '.jpg', result, function(err){
				if(err){
					sails.log.error('Download file [' + file.mediaid + '] from wechat server.');
					sails.log.error(err);
				}else{
					sails.log.info('Downloaded file [' + file.mediaid + '] from wechat server.');
				}
				cb();
			});
		});
		
	},
};
